/**
 * @description 足球篮球赛事详情
 */
export default {
	data() {
		return {
			navBgColor: 'rgba(0,0,0,0)', //导航栏背景色
			
			matchId: null, //比赛ID
			match: {}, //比赛信息对象
			isFavMatch: false, //是否已关注比赛
			
			tabList: [//tab信息
				{name: '方案'},{name: '联赛排行'},{name: '直播'},{name: '指数'}
			],
			tabArr: [0], //记录tab访问状态
			tabCur: 0, //当前tab
			tabData: [ //tab分页数据
				{pageNo: 1,	isEnd: false},
				{pageNo: 1,	isEnd: false},
				{pageNo: 1,	isEnd: false},
				{pageNo: 1,	isEnd: false}
			],
			
			matchLive: {}, //直播数据
			matchStatsData: [], //比赛技术统计数据
			matchTextLiveData: [], //比赛文字直播数据
			articleList: [], //比赛方案
			seasonRank: [], //联赛排行
			matchZsList: [], //比赛指数数据
			zsMathInfo: [], //比赛指数统计数据
			
			scrollTop: 0, //滚动位置
			currentTop: [0, 0, 0, 0], //当前滚动位置记录
			navBorder: false, 
			refreshing: false,
			
			visible: false //关注提醒弹窗是否展示
		}
	},
	components: {
		SeasonRank: () => import("../components/ch-expert/ch-seasonrank.vue"), //联赛排行
		MatchRemind: () => import('@/components/ch-match/ch-matchremind.vue') //比赛关注提醒
	},
	computed: {
		user() {
			return this.$store.state.user
		},
		//当前指数类型
		zsType() {
			return this.zsTypeData[this.indexTab.tabCur]
		},
		//客队名称
		awatTeam() {
			if(this.match.awayNameZh)
				return this.match.awayNameZh
			else
				return ''
		},
		//主队名称
		homeTeam() {
			if(this.match.homeNameZh)
				return this.match.homeNameZh
			else
				return ''
		},
		//最新比赛状态
		statusId() {
			if(this.matchLive.score){
				let json = JSON.parse(this.matchLive.score)
				if(json[1] >= this.match.statusId){
					return json[1]
				}else{
					return this.match.statusId
				}
			}else if(this.match.statusId){
				return this.match.statusId
			}else{
				return 0
			}
		}
	},
	watch: {
		//解析比赛得分数据
		match(newValue){
			if(this.matchLive.score == null){
				if(typeof newValue.homeScores == 'string'){
					this.match.homeScores = JSON.parse(newValue.homeScores)
					this.match.awayScores = JSON.parse(newValue.awayScores)
				}
			}else{
				let json = JSON.parse(this.matchLive.score)
				if(this.sportId == 1){
					this.match.homeScores = json[2]
					this.match.awayScores = json[3]
				}else{
					this.match.homeScores = json[3]
					this.match.awayScores = json[4]
				}
			}
		},
		//直播数据比分更新
		matchLive(newValue) {
			if(newValue.score && this.match){
				let json = JSON.parse(newValue.score)
				if(this.sportId == 1){
					this.match.homeScores = json[2]
					this.match.awayScores = json[3]
				}else{
					this.match.homeScores = json[3]
					this.match.awayScores = json[4]
				}
			}
		}
	},
	onLoad() {
		if(this.$Route.query.mid){
			this.matchId = this.$Route.query.mid
		}
		if(this.matchId){
			this.getMatchInfo() //查询比赛基础信息
			this.getArticles() //查询比赛方案
			//this.getMatchLive()
		}else{
			//非法请求处理
			uni.showToast({
				title: '请求数据错误，请返回重试',
				icon: 'none'
			})
			this.$goBack(1)
		}
	},
	methods:{
		//屏幕滑动监听
		scroll(e) {
			this.scrollTop = e.detail.scrollTop
			this.currentTop[this.tabCur] = e.detail.scrollTop
			
			if(e.detail.scrollTop > 10){
				this.navBorder = true
			}else{
				this.navBorder = false
			}
		},
		//下拉刷新
		refresh() {
			this.refreshing = true
			if(this.tabCur == 0){
				this.tabData[0].pageNo = 1
			}
			this.getListData(this.tabCur)
			setTimeout(() => {
				this.refreshing = false
			}, 1000)
		},
		//选项卡切换
		tabChange(index) {
			this.tabCur = index;
			this.$nextTick(()=>{
				this.scrollTop = this.currentTop[index]
			})
			if(this.tabArr.indexOf(index) < 0){
				this.tabArr.push(index)
				this.getListData(index)
			}
			//日志访问统计
			if( index != 0 ){
				let fromIndex = this.$Route.meta.routeName
				let toIndex = this.tabList[index].name
				if(fromIndex) {
					this.$CHS.saveVisitLog(fromIndex, toIndex)
				}
			}
		},
		//触摸滑动开始
		touchStart(e) {
			if (e.changedTouches.length == 1) {
				this.startX = e.changedTouches[0].clientX
				this.startY = e.changedTouches[0].clientY
			}
		},
		//触摸滑动结束
		touchEnd(e) {
			if (e.changedTouches.length == 1) {
				var endX = e.changedTouches[0].clientX;
				var endY = e.changedTouches[0].clientY;
				var xTowards = endX - this.startX;
				var yTowards = endY - this.startY;
				if (xTowards > 50 && Math.abs(yTowards) < 50) {//向右
					console.log('向右')
					if(this.tabCur > 0){
						if(this.tabCur == 2 && !this.seasonRank[0]){
							this.tabChange(0)
						}else{
							this.tabChange(this.tabCur - 1)
						}
					}
				}
				if (xTowards < -50 && Math.abs(yTowards) < 50) {//向左
					console.log('向左')
					let maxlen = this.tabData.length - 1;
					if(this.tabCur < maxlen){
						if(this.tabCur == 0 && !this.seasonRank[0]){
							this.tabChange(2)
						}else{
							this.tabChange(this.tabCur + 1)
						}
					}
				}
			}
		},
		//指数选项卡切换
		indexTabChange(index) {
			this.indexTab.tabCur = index
			if(!this.matchZsList[this.zsType]){
				this.getMatchZsDetails()
			}
		},
		//获取数据
		getListData(index) {
			if(index == 0){
				this.getArticles()
			}
			if(index == 1 && this.match.seasonId){
				this.getSeasonRank(this.match.seasonId)
			}
			if(index == 2){
				if(this.sportId == 2){
					this.livePeriod = 0
				}
				this.getMatchLive()
			}
			if(index == 3){
				this.getMatchZsDetails()
			}
		},
		//比赛基础信息
		getMatchInfo() {
			this.$http.get({
				url: '/api/queryMatchBaseInfo',
				data: {
					matchId: this.matchId,
					sportId: this.sportId
				},
			}).then(data => {
				console.log(data);
				if(data.success && data.result){
					this.match = data.result
					this.isFavMatch = data.result.followStatus == 1
					if(data.result.seasonId){
						this.tabArr.push(1)
						this.getListData(1)
					}
				}else{
					this.$ShowToast({text: '比赛信息加载失败', type: 2})
					setTimeout(()=>{
						this.$goBack(1)
					}, 1000)
				}
			}).catch((err) => {
				console.log(err);
			})
		},
		//比赛相关料
		getArticles(pageNo=1) {
			this.$http.get({
				url: '/api/user/article/gameArticle',
				data: {
					matchId: this.matchId,
					sportId: this.sportId,
					pageNo,
					pageSize: 50,
				},
			}).then(data => {
				console.log(data,'比赛料');
				if(data.success && data.result && data.result.total){
					if(pageNo == 1){
						this.articleList = data.result.records
					}else{
						this.articleList.push(...data.result.records)
					}
					this.tabData[this.tabCur].isEnd = pageNo >= data.result.pages
				}
			}).catch((err) => {
				console.log(err);
			})
		},
		//联赛排行榜
		getSeasonRank(seasonId){
			this.$http.get({
				url: '/api/appUser/querySeasonExpertRankRows',
				data: {
					sportId: this.sportId,
					seasonId,
					userId: this.user.userId
				}
			}).then((data)=>{
				console.log(data);
				if(data.success && data.result){
					this.seasonRank = data.result
				}else{
					this.seasonRank = []
				}
			})
		},
		//比赛直播数据
		getMatchLive() {
			this.$http.get({
				url: '/api/queryLive',
				data: {
					matchId: this.matchId,
					sportId: this.sportId
				},
			}).then(data => {
				console.log(data);
				if(data.success && data.result){
					this.matchLive = data.result
				}
			}).catch((err) => {
				console.log(err);
			})
		},
		//指数信息
		getMatchZsDetails() {
			this.$http.get({
				url: '/api/oddsList',
				data: {
					matchId: this.matchId,
					sportId: this.sportId,
					zsType: this.zsType
				},
			}).then(data => {
				console.log(data);
				if(data.success && data.result[0]){
					this.$set(this.matchZsList, this.zsType, data.result)
					if(this.zsType == 'eu'){
						this.getZsMathInfo()
					}
				}
			}).catch((err) => {
				console.log(err);
			})
		},
		//查看指数详情
		goZsDetail(zsType,index) {
			let id = this.indexTab.tabCur.toString() + '_' + index + '_' +this.matchId
			let params = {mid: id,}
			if(this.sportId == 1){
				this.$goByName('matchzsfoot', params)
			}else{
				this.$goByName('matchzsbasket', params)
			}
		},
		//选择提醒时间
		seletRemindTime() {
			if(!this.$store.state.isLogin){
				this.$CHS.goUserLogin()
				return
			}
			if(this.statusId == 1){
				if(this.isFavMatch){
					this.visible = false
					this.favMatch()
				}else{
					this.visible = true
				}
			}
		},
		//比赛关注or取消
		favMatch(remindTime) {
			if(this.isFaving){
				return
			}
			if(this.isFavMatch){
				var url = '/api/appUser/upcareUserFollow'
			}else{
				var url = '/api/appUser/careUserFollow'
			}
			this.isFaving = true
			this.$http.post({
				url: url,
				data: {
					commonId: this.match.matchId,
					remindTime,
					sportId: this.sportId,
					type: 3,
					userId: this.user.userId,
				},
			}).then(data => {
				console.log(data);
				if(data.success){
					this.isFavMatch = !this.isFavMatch
					let match = {
						sportId: this.sportId,
						matchId: this.match.matchId
					}
					if(this.isFavMatch){
						this.$store.commit('IS_FOLLOW_MATCH', match)
						this.$ShowToast({text: '已收藏', type: 1})
					}else{
						this.$store.commit('NO_FOLLOW_MATCH', match)
						this.$ShowToast({text: '已取消收藏', type: 1})
					}
				}else{
					uni.showToast({
						title: data.message,
						icon: 'error'
					})
				}
			}).catch((err) => {
				console.log(err);
			}).finally(()=>{
				this.isFaving = false
			})
		},
		//获取特殊时间
		getDateStr(datetime) {
			let weekDay = ['周日','周一','周二','周三','周四','周五','周六'];
			datetime = datetime.replace(/-/g, "/")
		    let dd = new Date(datetime); 
			let week = dd.getDay();
			console.log(weekDay[week]);
			return weekDay[week]
		},
		//指数平均值最大值最小值计算
		getZsMathInfo() {
			console.log(this.matchZsList,"-----")
			let initialValue = new Array([],[],[])
			let beforeStart = new Array([],[],[])
			let defaultObj = {
				homeWin: 0,
				drawWin: 0,
				awayWin: 0
			}
			this.matchZsList.eu.forEach(item =>{
				if(!item.initialValue){
					item.initialValue = {
						...defaultObj
					}
				}
				if(!item.beforeStart){
					item.beforeStart = {
						...defaultObj
					}
				}
				// if(item.initialValue && item.beforeStart){
				// 	initialValue[0].push(item.initialValue.homeWin)
				// 	initialValue[1].push(item.initialValue.drawWin)
				// 	initialValue[2].push(item.initialValue.awayWin)
				// 	beforeStart[0].push(item.beforeStart.homeWin)
				// 	beforeStart[1].push(item.beforeStart.drawWin)
				// 	beforeStart[2].push(item.beforeStart.awayWin)
				// }
				initialValue[0].push(item.initialValue.homeWin)
				initialValue[1].push(item.initialValue.drawWin)
				initialValue[2].push(item.initialValue.awayWin)
				beforeStart[0].push(item.beforeStart.homeWin)
				beforeStart[1].push(item.beforeStart.drawWin)
				beforeStart[2].push(item.beforeStart.awayWin)
			})
			console.log(initialValue[0]);
			let maxZs = new Array([],[])
			maxZs[0].push(Math.max(...initialValue[0]))
			maxZs[0].push(Math.max(...initialValue[1]))
			maxZs[0].push(Math.max(...initialValue[2]))
			maxZs[1].push(Math.max(...beforeStart[0]))
			maxZs[1].push(Math.max(...beforeStart[1]))
			maxZs[1].push(Math.max(...beforeStart[2]))
			console.log(maxZs);
			this.zsMathInfo.push(maxZs)
			let minZs = new Array([],[])
			minZs[0].push(Math.min(...initialValue[0]))
			minZs[0].push(Math.min(...initialValue[1]))
			minZs[0].push(Math.min(...initialValue[2]))
			minZs[1].push(Math.min(...beforeStart[0]))
			minZs[1].push(Math.min(...beforeStart[1]))
			minZs[1].push(Math.min(...beforeStart[2]))
			console.log(minZs);
			this.zsMathInfo.push(minZs)
			let avgZs = new Array([],[])
			avgZs[0].push(this.getAvg(initialValue[0]))
			avgZs[0].push(this.getAvg(initialValue[1]))
			avgZs[0].push(this.getAvg(initialValue[2]))
			avgZs[1].push(this.getAvg(beforeStart[0]))
			avgZs[1].push(this.getAvg(beforeStart[1]))
			avgZs[1].push(this.getAvg(beforeStart[2]))
			console.log(avgZs);
			this.zsMathInfo.push(avgZs)
		},
		//平均值
		getAvg(valueArr){
			let arr = Array.from(valueArr)
			let sumTotal = eval(arr.join('+'))
			console.log(sumTotal);
			let avg = sumTotal / arr.length
			return avg.toFixed(2)
		},
		//星期文字转换
		weekDay(day) {
			return this.$CHS.weekStr[day-1]
		}
	}
}